from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.contrib.auth.models import User  
from django.contrib.auth.forms import UserCreationForm
from django.contrib import auth
from django.template import RequestContext


def home(request):
	return render_to_response("index.html");

def hello(request):
    return HttpResponse("Hello world")
	
def test(request):
	if "favorite_color" in request.GET:
		return set_color(request)
	else:
		return render_to_response("test.html");

def register(request):
	if request.method == 'POST':
		form = UserCreationForm(request.POST)
		if form.is_valid():
			new_user = form.save()
			return HttpResponseRedirect("/hello/")
	else:
		form = UserCreationForm()
	return render_to_response("registration/register.html", {'form': form},context_instance=RequestContext(request))

def login(request):
	if request.method != 'POST':
		return render_to_response("registration/login.html",context_instance=RequestContext(request))
	else:
		return login_view(request);

def login_view(request):
	username = request.POST.get('username', '')
	password = request.POST.get('password', '')
	user = auth.authenticate(username=username, password=password)
	if user is not None and user.is_active:
		# Correct password, and the user is marked "active"
		auth.login(request, user)
		# Redirect to a success page.
		return HttpResponseRedirect("/hello/")
	else:
		# Show an error page
		form = UserCreationForm()
		return render_to_response("registration/register.html", {'form': form},context_instance=RequestContext(request))


def logout(request):
    auth.logout(request)
    # Redirect to a success page.
    return HttpResponseRedirect("/account/loggedout/")

def show_color(request):
    if "favorite_color" in request.COOKIES:
        return HttpResponse("Your favorite color is %s" % request.COOKIES["favorite_color"])
    else:
        return HttpResponse("You don't have a favorite color.")

def set_color(request):
    if "favorite_color" in request.GET:

        # Create an HttpResponse object...
        response = HttpResponse("Your favorite color is now %s" % request.GET["favorite_color"])

        # ... and set a cookie on the response
        response.set_cookie("favorite_color",request.GET["favorite_color"])

        return response

    else:
        return HttpResponse("You didn't give a favorite color.")